﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using RouterControl.Whs.Wizards;
using Microsoft.HomeServer.Controls;
using RouterControl.IO.UPnP;
using System.Runtime.InteropServices;
using RouterControl.IO;

namespace RouterControl.WhsAddIn.Wizards.SelectRouter
{
    public partial class PageSearch : WizardPageClientBannerTop
    {
        private readonly log4net.ILog _log = log4net.LogManager.GetLogger(typeof(PageSearch));

        private WizardMain ParentWizardMain
        {
            get { return (WizardMain)this.ParentWizard; }
        }

        public PageSearch()
        {
            InitializeComponent();
        }

        private void PageSearch_BackButtonClick(object sender, EventArgs e)
        {
            this.SetCurrentPage<PageAllowUpload>();
        }

        public override void StartRealWork()
        {
            base.StartRealWork();

            // gather information
            var info = this.ParentWizardMain.UsageInfo;

            info.ExitPage = GetType().Name;

            // continue
            this.labelResult.Text = Resources.txtPleaseWait;

            this.searchBgWorker.RunWorkerAsync();
        }

        private void searchBgWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            _log.Info("Searching for routers natively...");

            try
            {
                var finder = new UPnPDeviceFinderClass();

                var devices = finder.FindByType(
                    IO.RootDeviceTypeIds.InternetGatewayDeviceType,
                    IO.RootDeviceTypeIds.InternetGatewayDslDeviceType
                    );

                _log.InfoFormat("Found {0} routers (native)", devices.Count);

                // add to usage information
                this.ParentWizardMain.UsageInfo.FoundRoutersCount = devices.Count;

                // inform the user
                this.labelResult.Text = string.Format(
                    Resources.txtDevicesFound,
                    devices.Count
                    );

                // finalize
                this.ParentWizardMain.FoundDevices = devices;
            }
            catch (Exception ex)
            {
                _log.Error("Failed to find routers natively", ex);

                throw;
            }
        }

        private void searchBgWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            this.SetCurrentPage<PageRouterList>();
        }
    }
}